<?php

namespace Modules\Api\Controllers;

use Lib\Medoo;
use Lib\Response;
use Lib\Consts;
use Models\Api\DsDatabase;
use Models\Api\Manager;
use Models\Api\RoleRule;
use Models\Api\Rule;
use Models\Api\Role;
use Models\Api\User;
use Phalcon\Paginator\Adapter\QueryBuilder;

class DatabaseController extends ControllerBase {


    public function listAction() {
        $page = $this->json("page", null,1);
        $limit  = 20;
        $where  = "status!='已删除'";
        $mapper = new DsDatabase();

//        { "id": "1", "name": "测试数据库", "type": "mysql", "ip": "rm-bp1311o2xle56fuom5m.mysql.rds.aliyuncs.com", "port": "3306", "username": "lvsong",
// "password": "!KQnpjLdyLG^2k9b", "dbname": "dev_bigdata", "parameter": null, "remark": null, "status": "1", "create_time": null, "update_time": null } ] }

        $builder = $mapper->getModelsManager();
        $builder = $builder->createBuilder();
        $builder->where($where);
        $builder->columns(["id","name","type","dbname","parameter","remark","status","create_time","update_time"]);
        $builder->from('Models\Api\DsDatabase');
        $builder->orderBy('id DESC');

        $paginator = new QueryBuilder([
            'builder' => $builder,
            'limit'   => $limit,
            'page'    => $page,
        ]);

        $pageData = $paginator->getPaginate();
//        $data     = $pageData->items->toArray();
        return Response::sucmsg($pageData);

    }

    // {"name": "测试数据库", "type": "mysql", "ip": "dev_bigdata", "port": 3306, "username": "username","password": "password", "dbname": "dev_bigdata", "parameter": null, "remark": null, "status": "1", "create_time": "2023-10-20 16:18:17", "update_time": null }
    public function addAction() {
        $name      = $this->json("name", "trim");
        $type      = $this->json("type");
        $ip        = $this->json("ip", "trim");
        $port      = $this->json("port", "trim");
        $username  = $this->json("username", "trim");
        $password  = $this->json("password", "trim");
        $dbname    = $this->json("dbname", "trim");
        $parameter = $this->json("parameter", "trim");
        $remark    = $this->json("remark", "trim");
        $status    = $this->json("status", "trim");

        $mapper = new DsDatabase();
        $mapper->setName($name);
        $mapper->setType($type);
        $mapper->setIp($ip);
        $mapper->setPort($port);
        $mapper->setUsername($username);
        $mapper->setPassword($password);
        $mapper->setDbname($dbname);
        $mapper->setParameter($parameter);
        $mapper->setRemark($remark);
        $mapper->setStatus($status);
        $mapper->setCreateTime(date("Y-m-d H:i:s"));

        $errMsg = $this->validate($mapper);

        if($errMsg !== false) {
            return Response::errmsg($errMsg, 10010);
        }

        $database = new Medoo([
            'database_type' => $type,
            'database_name' => $dbname,
            'server' => $ip,
            'port' => $port,
            'username' => $username,
            'password' => $password,
            'charset' => 'utf8'
        ]);

        if (!empty($database->errmsg)) {
            $mapper->setStatus("连接失败");
//            return Response::errmsg($database->errmsg, 10015);
        }

        try {
            $mapper->create();
            return Response::sucmsg([],"添加成功");
        } catch(\Exception $exc) {
            return Response::errmsg($exc->getMessage());
        }
    }

    public function editAction() {
        $id = $this->json("id", "trim");

        if(empty($id)) {
            return Response::errmsg("id不能为空", 10012);
        }

        $name = $this->json("name", "trim");
        $type = $this->json("type");
        $ip = $this->json("ip", "trim");
        $port = $this->json("port", "trim");
        $username = $this->json("username", "trim");
        $password = $this->json("password", "trim");
        $dbname = $this->json("dbname", "trim");
        $parameter = $this->json("parameter", "trim");
        $remark = $this->json("remark", "trim");
        $status = $this->json("status", "trim");

        $mapper = new DsDatabase();
        $model = $mapper->findFirst("id= $id AND status!=" . Consts::USER_DELETE);

        if(!$model) {
            return Response::errmsg("无此数据", 10013);
        }

//        var_dump($model->toArray());die();
        $model->setName($name);
        $model->setType($type);
        $model->setIp($ip);
        $model->setPort($port);
        $model->setUsername($username);
        $model->setPassword($password);
        $model->setDbname($dbname);
        $model->setParameter($parameter);
        $model->setRemark($remark);
        $model->setStatus($status);
        $model->setUpdateTime(date("Y-m-d H:i:s"));

        $errMsg = $this->validate($model);

        if($errMsg !== false) {
            return Response::errmsg($errMsg, 10012);
        }

        $database = new Medoo([
            'database_type' => $type,
            'database_name' => $dbname,
            'server' => $ip,
            'port' => $port,
            'username' => $username,
            'password' => $password,
            'charset' => 'utf8'
        ]);

        if (!empty($database->errmsg)) {
            $mapper->setStatus("连接失败");
//            return Response::errmsg($database->errmsg, 10015);
        }

        try {
            if ($model->update() === false) {
                return Response::errmsg('修改失败');
            }

            return Response::sucmsg([],"修改成功");
        } catch (\Exception $exc) {
            return Response::errmsg($exc->getMessage());
        }
    }

    private function validate(DsDatabase $mapper) {
        if(empty($mapper->getName())) {
            return '名称不能为空';
        }

        if(empty($mapper->getType())) {
            return '类型不能为空';
        }

        if($mapper->getType() != "mysql") {
            return '暂时只支持mysql数据库';
        }

        if(empty($mapper->getIp())) {
            return 'IP不能为空';
        }

        if(empty($mapper->getPort())) {
            return '端口不能为空';
        }

        if(empty($mapper->getUsername())) {
            return '用户名不能为空';
        }

        if(empty($mapper->getPassword())) {
            return '密码不能为空';
        }

        if(empty($mapper->getDbname())) {
            return '数据库名不能为空';
        }

        if($mapper->getStatus() != "正常" && $mapper->getStatus() != "禁用") {
            return '状态信息异常';
        }

        return false;
    }

    public function delAction() {
        $id = $this->json("id", "trim");

        if(empty($id)) {
            return Response::errmsg("id不能为空", 10012);
        }

        $mapper = new DsDatabase();
        $model  = $mapper::findFirst('id=' . $id);

        if (!$model instanceof DsDatabase) {
            return Response::errmsg('无此数据');
        }

        if ($model->getStatus() == "已删除") {
            return Response::errmsg('此数据已删除');
        }

        try {
            $model->setUpdateTime(date("Y-m-d H:i:s"));
            $model->setStatus("已删除");
            $model->save();
            return Response::errmsg('删除成功');
        } catch (\Exception $e) {
            return Response::errmsg($e->getMessage());
        }
    }

    public function getinfoAction() {
        $id = $this->json("id", "trim");

        if(empty($id)) {
            return Response::errmsg("id不能为空", 10013);
        }

        $mapper = new DsDatabase();
        $model  = $mapper::findFirst('id=' . $id);

        if (!$model instanceof DsDatabase) {
            return Response::errmsg('无此数据');
        }

        $model->setPassword("******");

        if ($model->getStatus() == Consts::USER_DELETE) {
            return Response::errmsg('此数据已删除');
        }

        return Response::sucmsg($model->toArray());
    }


    public function testAction() {
        $name = $this->json("name", "trim");
        $type = $this->json("type");
        $ip = $this->json("ip", "trim");
        $port = $this->json("port", "trim");
        $username = $this->json("username", "trim");
        $password = $this->json("password", "trim");
        $dbname = $this->json("dbname", "trim");
        $parameter = $this->json("parameter", "trim");
        $remark = $this->json("remark", "trim");
        $status = $this->json("status", "trim");

        $mapper = new DsDatabase();

        $mapper->setName($name);
        $mapper->setType($type);
        $mapper->setIp($ip);
        $mapper->setPort($port);
        $mapper->setUsername($username);
        $mapper->setPassword($password);
        $mapper->setDbname($dbname);
        $mapper->setParameter($parameter);
        $mapper->setRemark($remark);
        $mapper->setStatus($status);
        $mapper->setCreateTime(date("Y-m-d H:i:s"));

        $errMsg = $this->validate($mapper);

        if($errMsg !== false) {
            return Response::errmsg($errMsg, 10019);
        }

        $database = new Medoo([
            'database_type' => $type,
            'database_name' => $dbname,
            'server' => $ip,
            'port' => $port,
            'username' => $username,
            'password' => $password,
            'charset' => 'utf8'
        ]);

        //@todo 添加数据库连接测试至log

        if (!empty($database->errmsg)) {
            return Response::errmsg($database->errmsg, 10015);
        }

        return Response::sucmsg([],"连接成功");
    }


    /*

    protected function sendMsg() {
        $data = \Lib\Queue::pop('sms');

        //array(2) { ["mobile"]=> string(11) "18046303205" ["content"]=> int(5244) }
        if (!isset($data["mobile"]) || !isset($data["content"])) {
            return false;
        }

        $mobile  = $data["mobile"];
        $content = $data["content"];
        $demo    = new \Lib\Aliyun\Send();

        $response = $demo->sendSms(
            "自然浮图", "SMS_98265008", $mobile, ["code" => $content], "song"
        );

        return false;
    }

    public function sendAction() {
        $beginTime = time();

        while (time() - $beginTime < 59) {
            if ($this->sendMsg() === false) {
                sleep(1);
            }
        }

        return false;
    }*/
}